
package Comunicaciones;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 
 * 
 */
public class SocketCom {

/**
 * <p>Represents ...</p>
 * 
 */
    private Socket socket = null;

/**
 * <p>Represents ...</p>
 * 
 */
    private PrintWriter out = null;

/**
 * <p>Represents ...</p>
 * 
 */
    private BufferedReader in = null;

/**
 * <p>Does ...</p>
 * 
 * 
 * @param _socket 
 */
    public  SocketCom(Socket _socket) {        
        socket = _socket;
        try {
            out = new PrintWriter(socket.getOutputStream(),true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        }
        catch (IOException e) {
            e.printStackTrace();
            return;
        }
    } 

/**
 * <p>Does ...</p>
 * 
 * 
 * @param nombre_maquina 
 * @param puerto 
 */
    public  SocketCom(String nombre_maquina, int puerto) {        
        try {
            socket = new Socket(nombre_maquina, puerto);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Host desconocido: "+nombre_maquina);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error de conexion con: "+nombre_maquina);
            System.exit(1);
        }
    } 

/**
 * <p>Does ...</p>
 * 
 * 
 * @param mensaje 
 */
    public void enviar(String mensaje) {        
        out.println(mensaje);
    } 

/**
 * <p>Does ...</p>
 * 
 * 
 * @return 
 */
    public String recibir() {        
        String mensaje=null;
        try {
            mensaje=in.readLine();
        } catch (IOException e) {
             e.printStackTrace();
        }
        return mensaje;
    } 

/**
 * <p>Does ...</p>
 * 
 */
    public void terminar() {        
        try {
            out.close();
            in.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

/**
 * <p>Does ...</p>
 *
 */
    public String getPeerIP() {
       return socket.getInetAddress().getHostName();
    }

/**
 * <p>Does ...</p>
 *
 */
    public int getLocalPort() {
       return socket.getLocalPort();
    }
 }
